import { ref, reactive, onMounted, h, computed } from 'vue';
import { useMessage, useDialog, NSwitch } from 'naive-ui';
import {
  SearchOutline,
  AddOutline,
  CreateOutline,
  TrashOutline,
} from '@vicons/ionicons5';
import { createIndexColumn } from '@/utils/tableUtil';

export function useTitle() {
  const message = useMessage();
  const dialog = useDialog();

  // 搜索参数
  const searchParams = reactive({
    keyword: '',
    status: null as number | null,
  });

  // 状态选项
  const statusOptions = [
    { label: '启用', value: 1 },
    { label: '禁用', value: 0 },
  ];

  // 表格数据
  const loading = ref(false);
  const tableData = ref<any[]>([]);
  const pagination = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageCount: 0,
    onChange: (page: number) => {
      pagination.page = page;
      loadData();
    },
    onUpdatePageSize: (pageSize: number) => {
      pagination.pageSize = pageSize;
      pagination.page = 1;
      loadData();
    },
  });

  // 表格列定义
  const columns = computed(() => [
    createIndexColumn({
      currentPage: pagination.page,
      pageSize: pagination.pageSize,
    }),
    { title: '职称名称', key: 'name', width: 150 },
    { title: '职称等级', key: 'level', width: 100 },
    { 
      title: '状态', 
      key: 'status', 
      width: 100,
      render: (row: any) => {
        return h('div', { style: 'display: flex; align-items: center; gap: 8px;' }, [
          h(NSwitch, {
            value: row.status === 1,
            onUpdateValue: (value: boolean) => {
              // 更新数据中的状态
              row.status = value ? 1 : 0;
              console.log('状态切换:', row.id, value ? 1 : 0);
            }
          }),
          h('span', { style: 'font-size: 12px;' }, row.status === 1 ? '启用' : '禁用')
        ]);
      }
    },
    { title: '排序', key: 'sort', width: 100 },
    { title: '创建时间', key: 'createTime', width: 180 },
    { title: '备注', key: 'remark', width: 200 },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      render: (row: any) => {
        return h('div', [
          h(
            'n-button',
            {
              size: 'small',
              type: 'primary',
              ghost: true,
              onClick: () => handleEdit(row),
              style: 'margin-right: 8px',
            },
            { default: () => '编辑' }
          ),
          h(
            'n-button',
            {
              size: 'small',
              type: 'error',
              ghost: true,
              onClick: () => handleDelete(row),
            },
            { default: () => '删除' }
          ),
        ]);
      },
    },
  ]);

  // 表单相关
  const showModal = ref(false);
  const modalTitle = ref('新增职称');
  const submitLoading = ref(false);
  const formRef = ref();
  const formData = reactive({
    id: '',
    name: '',
    level: 1,
    status: 1,
    sort: 0,
    remark: '',
  });

  const rules = {
    name: {
      required: true,
      message: '请输入职称名称',
      trigger: 'blur',
    },
    level: {
      required: true,
      message: '请输入职称等级',
      trigger: 'blur',
    },
  };

  // 方法
  const rowKey = (row: any) => row.id;

  const loadData = () => {
    loading.value = true;
    // 模拟API调用
    setTimeout(() => {
      tableData.value = [
        {
          id: '1',
          name: '教授',
          level: 1,
          status: 1,
          sort: 1,
          createTime: '2024-01-15 10:30:00',
          remark: '最高职称等级',
        },
        {
          id: '2',
          name: '副教授',
          level: 2,
          status: 1,
          sort: 2,
          createTime: '2024-01-15 10:30:00',
          remark: '高级职称',
        },
        {
          id: '3',
          name: '讲师',
          level: 3,
          status: 1,
          sort: 3,
          createTime: '2024-01-15 10:30:00',
          remark: '中级职称',
        },
        {
          id: '4',
          name: '助教',
          level: 4,
          status: 1,
          sort: 4,
          createTime: '2024-01-15 10:30:00',
          remark: '初级职称',
        },
        {
          id: '5',
          name: '研究员',
          level: 1,
          status: 1,
          sort: 5,
          createTime: '2024-01-15 10:30:00',
          remark: '科研系列最高职称',
        },
        {
          id: '6',
          name: '副研究员',
          level: 2,
          status: 1,
          sort: 6,
          createTime: '2024-01-15 10:30:00',
          remark: '科研系列高级职称',
        },
      ];
      pagination.pageCount = 1;
      loading.value = false;
    }, 500);
  };

  const handleSearch = () => {
    pagination.page = 1;
    loadData();
  };

  const handleReset = () => {
    searchParams.keyword = '';
    searchParams.status = null;
    pagination.page = 1;
    loadData();
  };

  const handlePageChange = (page: number) => {
    pagination.page = page;
    loadData();
  };

  const handleAdd = () => {
    modalTitle.value = '新增职称';
    Object.assign(formData, {
      id: '',
      name: '',
      level: 1,
      status: 1,
      sort: 0,
      remark: '',
    });
    showModal.value = true;
  };

  const handleEdit = (row: any) => {
    modalTitle.value = '编辑职称';
    Object.assign(formData, row);
    showModal.value = true;
  };

  const handleDelete = (row: any) => {
    dialog.warning({
      title: '确认删除',
      content: `确定要删除职称"${row.name}"吗？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        message.success('删除成功');
        loadData();
      },
    });
  };

  const handleSubmit = () => {
    formRef.value?.validate((errors: any) => {
      if (!errors) {
        submitLoading.value = true;
        setTimeout(() => {
          message.success(formData.id ? '更新成功' : '创建成功');
          showModal.value = false;
          submitLoading.value = false;
          loadData();
        }, 1000);
      }
    });
  };

  // 组件挂载时加载数据
  onMounted(() => {
    loadData();
  });

  return {
    // 搜索相关
    searchParams,
    statusOptions,
    // 表格相关
    loading,
    tableData,
    pagination,
    columns,
    rowKey,
    // 表单相关
    showModal,
    modalTitle,
    submitLoading,
    formRef,
    formData,
    rules,
    // 方法
    handleSearch,
    handleReset,
    handlePageChange,
    handleAdd,
    handleEdit,
    handleDelete,
    handleSubmit,
    // 图标组件
    SearchOutline,
    AddOutline,
    CreateOutline,
    TrashOutline,
  };
} 